<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>上传</title>
</head>

<body>
  <input type="file" id="file">
  <script>
    file.addEventListener('change', async (e) => {
      const file = e.target.files[0] //es6文件对象
      const fileName = file.name.split('.')[0]

      let cur = 0, size = 1024 * 1024 // 1M
      // cur 开始， size 大小
      const fileChunkList = []
      while (cur < file.size) {
        fileChunkList.push({
          file: file.slice(cur, cur + size)
        })
        cur += size
      }
      const requestList = fileChunkList
        .map(({ file }, index) => {
          const formData = new FormData()
          formData.append("chunk", file)
          formData.append("fileName", `${fileName}-${index}`)
          return { formData }
        })
        .map(async ({ formData }) => request({
          url: 'http://localhost:3000',
          data: formData,
        }))
      await Promise.all(requestList) // 并发
      console.log(requestList);
    })

    const request = ({
      url,
      method = "POST",
      data,
      headers = {},
      requestList, // 文件列表
    }) =>
      new Promise(resolve => {
        const xhr = new XMLHttpRequest()
        xhr.open(method, url)
        Object.keys(headers).forEach(key =>
          xhr.setRequestHeader(key, headers[key]) // 请求头
        )
        xhr.send(data)
        xhr.onload = e => {
          resolve({
            data: e.target.response
          })
        }
      })
  </script>
</body>

</html>